package config

import (
	"com.yy.api/common/client/agent/api"
	"com.yy.api/common/config"
	"com.yy.api/common/logger"
	"fmt"
	rediz "github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"path/filepath"
	"runtime"
)

var (
	cfg     *config.Config
	AppPort string
)

func init() {
	_, currentFilePath, _, _ := runtime.Caller(0)
	currentDir := filepath.Join(filepath.Dir(currentFilePath))
	fmt.Printf("%v", currentDir)
	env := os.Getenv("APP_ENV")
	if env == "prod" {
		cfg = config.LoadConfig(currentDir, "app-prod")
	} else {
		cfg = config.LoadConfig(currentDir)
	}
	AppPort = cfg.LoadAppConfig().GetPort()
}
func GetDBConnection() *gorm.DB {
	dbConfig := cfg.LoadDBConfig()
	conn, err := gorm.Open(mysql.Open(dbConfig.GetConnectionString()), &gorm.Config{})
	fmt.Printf("%s", dbConfig.GetConnectionString())
	if err != nil {
		logger.Default.Errorf("连接数据库失败: %v", err)
	}
	if conn == nil {
		logger.Default.Error("数据库连接为空")
		return nil
	}
	return conn
}

func GetRedisClient() *rediz.Client {
	redisConfig := cfg.LoadRedisConfig()
	return rediz.NewClient(&rediz.Options{
		Addr:     redisConfig.GetAddrString(),
		Password: redisConfig.Password,
		DB:       redisConfig.DB,
	})
}

func GetAgentClient() *api.AgentClient {
	agentConfig := cfg.LoadAgentConfig()
	client, err := api.NewAgentClient(agentConfig.GetAddrString())
	fmt.Println(agentConfig.GetAddrString())
	if err != nil {
		logger.Default.Errorf("Fail to initialize agent connection", err)
		return nil
	}
	return client
}
